<?php
class m_website_services_FreeContentService extends f_core_Service
{
	/**
	 * @var m_website_services_FreeContentService
	 */
	private static $instance;
	
	/**
	 * Constructor
	 */
	private function __construct()
	{
		// Code if needed...
	}
	
	/**
	 * @return m_website_services_FreeContentService
	 */
	public static function getInstance()
	{
		if (self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	
    public function parseContent($content, $lang)
    {
        $content = stripslashes($content);

        preg_match_all('/{{mediaUrl docId=(.*?) fileName=\'(.*?)\'}}/', $content, $results);
        if(isset($results) && is_array($results))
        {
            $docProvider = $this->getDocumentProvider();

            foreach($results[0] as $k => $tag)
            {
                $id = $results[1][$k];
                $fileName = $results[2][$k];

                $replace = "";

                if($docProvider->checkDocument($id, $lang))
                {
                    $media = $docProvider->getByUniqueId($id, $lang);
                    $replace = $media->getFileUrl($fileName);
                }

                $content = str_replace($tag, $replace, $content);
            }
        }
        return $content;
    }

    public function parseImages($content)
    {
        preg_match_all('/<img (.*?)\/>/',$content, $matches);

        if(count($matches[0]) > 0)
        {
            foreach($matches[0] as $k => $tag)
            {
                $tagContent = $matches[1][$k];
                preg_match('/src="(.*?)"/', $tagContent, $res);
                $src = $res[1];

                preg_match('/id="picture_(.*?)"/', $tagContent, $res);
                $id = isset($res[1]) ? $res[1] : null;

                if(!is_null($id))
                {
                    if(!preg_match('/{{.*}}/', $src))
                    {
                        $exp = explode('/', $src);
                        $fileName = end($exp);

                        $newSrc = '{{mediaUrl docId='.$id.' fileName=\''.$fileName.'\'}}';
                        $content = str_replace($src, $newSrc, $content);
                    }
                }
                else
                {
                    $mediasRootNode = m_backoffice_services_RootNodeService::getInstance()->getModuleRootNode('medias');
                    $folder = f_target_Manager::getDocumentByUniqueTarget('downloadFolder', $mediasRootNode->getId());

                    if(is_object($folder) && $folder->getModel() == 'modules_backoffice/folder')
                    {
                        $exp = explode('/', $src);
                        $fileName = end($exp);

                        $distImg = fopen($src, 'rb');
                        $distContent = stream_get_contents($distImg);
                        fclose($distImg);

                        $destDir = $this->getDestPath($folder);

                        if(!is_dir($destDir))
                        {
                            mkdir($destDir, 0777, true);
                        }

                        $newImg = fopen($destDir.$fileName, 'w');
                        fwrite($newImg, $distContent);
                        fclose($newImg);

                        $media = $this->saveMedia($destDir, $fileName, $folder);

                        $newSrc = '{{mediaUrl docId='.$media->getId().' fileName=\''.$fileName.'\'}}';
                        $content = str_replace($src, $newSrc, $content);
                    }
                }
            }
        }

        return $content;
    }

    private function saveMedia($filePath, $fileName, $folder)
    {
        $media = m_medias_documents_Media::createNew();

        $fileObj = f_file_File::getInstance($filePath.$fileName);

        $media	->setMime($fileObj->getMimeType())
                ->setAuthor("pagizer")
                ->setExt($fileObj->getExtension())
                ->setLabel($fileName)
                ->setAlt($fileObj->getFileName())
                ->setTitle($fileObj->getFileName())
                ->save(false);

        $folder->addMedia($media)->save(false);

        if($media->isImage())
        {
            $media->createIcon();
            $media->createMceIcon();
            $media->createPreview();

            $parameters = m_medias_services_ParameterService::getInstance()->getParametersByFolderId($folder->getId(), $folder->getLang());

            if(!is_null($parameters))
            {
                /* @var $parameter m_medias_documents_Parameter */
                foreach($parameters as $parameter)
                {
                    if($parameter->isGenerateOnUpload())
                    {
                        $media->advancedResizePicture($parameter->getWidth(), $parameter->getHeight(), $parameter->getCrop());
                    }
                }
            }
        }

        return $media;
    }

    private function getDestPath($folder)
    {
        $parents = f_relation_Manager::getInstance()->getParentsIdsByDocType($folder->getId(), "modules_backoffice/folder", $folder->getLang());

        if(!is_array($parents))
        {
            $parents = array();
        }
        else
        {
            foreach($parents as $parent)
            {
                $result[] = $parent['parent_id'];
            }

            $parents = $result;
        }

        array_push($parents, $folder->getId());
        array_push($parents, strtolower($folder->getLang()));

        $parents = join(DS, $parents);

        $destPath = HTTP_DIR.DS."images".DS.$parents.DS;
        return $destPath;
    }
}